import React, { Component } from 'react'
import { Switch, Route, Redirect, withRouter } from 'react-router'
const Index = React.lazy(()=>import('../component/Index'))
const Redux = React.lazy(()=>import('../component/Redux'))
const Redux2 = React.lazy(()=>import('../component/Redux2'))
const Login = React.lazy(()=>import('../component/Login'))
const Cart = React.lazy(()=>import('../component/Cart'))
// 路由表，一个数组
const routes = [
  {
    path: '/',
    component: Index,
    exact: true,
    isLogin: false,
    meta: {
      title: '首页'
    }
  },
  {
    path: '/login',
    component: Login,
    exact: true,
    isLogin: false,
    meta: {
      title: '登录'
    }
  },
  {
    path: '/cart',
    component: Cart,
    exact: true,
    isLogin: true,
    meta: {
      title: '购物车'
    }
  },
  {
    path: '/redux',
    component: Redux,
    exact: true,
    isLogin: false,
    meta: {
      title: 'redux'
    }
  },
  {
    path: '/redux2',
    component: Redux2,
    exact: true,
    isLogin: false,
    meta: {
      title: 'redux2'
    }
  },
]
export default class Router extends Component {
  render() {
    return (
      <React.Suspense fallback={<mark>loading...</mark>}>
        <Switch>
          {routes.map((item, index) => {
            return (
              <Route path={item.path} key={index} exact={item.exact} 
              render={()=>{
                document.title = item.meta.title || 'orange';
                // 页面不需要登录
                if(!item.isLogin) {
                  // withRouter保证是一个路由组件
                  const Com = withRouter(item.component);
                  return <Com></Com>
                }else {
                  // 这些组件是需要登录后才能查看的，要检查登录状态
                  if(localStorage.getItem('isLogin')) {
                    // 已经登陆
                    const Com = withRouter(item.component);
                    return <Com></Com>
                  }else {
                    // 没有登录
                    return <Redirect to="/login"></Redirect>
                  }
                }
              }}
              ></Route>
            )
          })}
        </Switch>
      </React.Suspense>
    )
  }
}
